<template>
  <a-layout-sider width="200" style="background: #fff">
    <a-menu
      v-model:selectedKeys="current"
      mode="inline"
      :items="menuItems"
      @click="doMenuClick"
    ></a-menu>
  </a-layout-sider>
</template>
<script setup lang="ts">
import { PictureOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons-vue'
import { computed, h, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import { SPACE_LEVEL_ENUM } from '@/constants/spaceConstant.ts'
import { SPACE_TYPE_ENUM } from '@/constants/spaceUserConstant.ts'
import { listMySpaceUserUsingGet, listMyTeamSpaceUserUsingGet } from '@/request/api/spaceUserController.ts'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useUserLoginStore.ts'

const fixedMenuItems = [
  {
    key: '/',
    label: '公共图库',
    icon: () => h(PictureOutlined),
  },
  {
    key: '/my-space',
    label: '我的空间',
    icon: () => h(UserOutlined),
  },
  {
    key: `/add-space?type=${SPACE_TYPE_ENUM.TEAM}`,
    label: '创建团队空间',
    icon: () => h(TeamOutlined),
  },
]
const teamSpaceList = ref<API.SpaceUserVO[]>([])
const menuItems = computed(() => {
  // 没有团队空间就显示固定的
  if (teamSpaceList.value.length < 1) {
    return fixedMenuItems
  }
  // 展开的空间分组菜单
  const teamSpaceSubMenu=teamSpaceList.value.map((spaceUser) => {
    const space=  spaceUser.space
    return {
      key: `/space/${spaceUser.spaceId}`,
      label: space?.spaceName,
    }
  })
  // 添加个组
  const teamSpaceMenuGroup={
    type: 'group',
    key: 'team-space',
    label: '团队空间',
    children: teamSpaceSubMenu
  }
  return [...fixedMenuItems, teamSpaceMenuGroup]
})
// 菜单当前高亮的列表
const current = ref<string[]>([])
const router = useRouter()
router.afterEach((to, from, failure) => {
  current.value = [to.fullPath]
})
const doMenuClick = ({ key }: { key: string }) => {
  router.push(key)
}
const fetchTeamSpaceList = async () => {
  const { data:res } = await listMyTeamSpaceUserUsingGet()
  if (res.code==0 && res.data) {
    teamSpaceList.value = res.data
  } else {
    message.error("加载我的空间失败,",res.message)
  }
}
const loginUserStore = useLoginUserStore()
// 监听方法里的所有属性，任意个发生改变时触发
watchEffect(()=> {
  // 当用户登录时，获取用户团队空间信息
  if (loginUserStore.loginUser?.id) {
    fetchTeamSpaceList()
  }
})
</script>
<style scoped lang="less"></style>
